﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

//演示静态方法
public class Test_GameObject1 : MonoBehaviour
{
    public GameObject prefab;

    private void Update1()
    {
        if (Input.GetMouseButtonDown(0))
        {
            GameObject go = Instantiate(prefab, Vector3.zero, Quaternion.identity);//实例化(预制体,位置,旋转)
            //后续还可以对go进行操作
            Rigidbody rig = go.AddComponent<Rigidbody>();//添加刚体组件
            //Destroy(rig);//移除组件
            //Destroy(go);//销毁游戏物体
            Destroy(go, 3);//延迟销毁或移除组件
        }
    }

    private void Start1()
    {
        //根据名称找
        //GameObject go = GameObject.Find("Plane");
        GameObject go = GameObject.FindGameObjectWithTag("A");
        go.GetComponent<MeshRenderer>().material.color = Color.yellow;
        //根据标签查找所有相同标签的物体
        GameObject[] array = GameObject.FindGameObjectsWithTag("A");
        foreach (var item in array)
        {
            item.GetComponent<MeshRenderer>().material.color = Color.blue;
        }
    }

    #region 根据类型找组件

    private Camera cam;//摄像机

    private void Start()
    {
        cam = FindObjectOfType<Camera>();//找到主摄像机上的摄像机组件
    }

    private void Update2()
    {
        if (Input.GetMouseButtonDown(1))//鼠标右键
        {
            cam.fieldOfView = cam.fieldOfView == 60 ? 30 : 60;
        }
    }

    private void Update()
    {
        Transform[] array = FindObjectsOfType<Transform>();//找到所有Transform组件
        for (int i = 0; i < array.Length; i++)
        {
            Destroy(array[i].gameObject);//销毁Transform组件所在的游戏物体
        }
    }

    #endregion 根据类型找组件
}

//演示每一个GameObject对象的方法
internal class Test_GameObject : MonoBehaviour
{
    private Camera cam;//定义变量
    private GameObject lightGo;

    private void Start()
    {
        cam = this.gameObject.GetComponent<Camera>();//获取组件
        //Destroy(camera);
        cam.depth = 0;
        lightGo = GameObject.Find("Directional Light");
    }

    private void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space))//按下空格
        {
            Test_Input t = this.gameObject.AddComponent<Test_Input>();//会返回添加的组件对象
            Destroy(t);
        }
        if (Input.GetMouseButtonDown(0))
        {
            lightGo.SetActive(false);//禁用游戏物体
        }
        if (Input.GetMouseButtonDown(1))
        {
            lightGo.SetActive(true);//激活游戏物体
        }
    }
}